package com.gosuncn.utils;

import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @Description: word和pdf转换
 * @Author: xiaolong
 * @date: 2022/3/16 14:25
 * @Version: 1.0
 */
public class FileUtil {


    /**
     * 导入word文档
     * @param data 数据
     * @param fileName 文件名
     * @param response response
     */
    public static void exportWord(String data, String fileName, HttpServletResponse response){
        try (InputStream in = IOUtils.toInputStream(data,"utf-8"); OutputStream out = response.getOutputStream();){
            //设置拓展头，当Content-Type 的类型要下载的类型时，这个信息头回告诉浏览器这个文件的名字何类型
            String contentType = new MimetypesFileTypeMap().getContentType(fileName);
            response.setContentType(contentType);
            //设置编码
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,String.format("attachment; filename=%s", fileName));
            IOUtils.copy(in,out);
        }catch (Exception e){
            throw new IllegalArgumentException(e) ;
        }
    }


    /**
     * 导入pdf文档
     * @param data 数据
     * @param fileName 文件名
     * @param response response
     */
    public static void previewPDF(String data, String fileName, HttpServletResponse response){
        try (InputStream in = IOUtils.toInputStream(data,"utf-8");OutputStream out = response.getOutputStream();){
            //设置拓展头，当Content-Type 的类型要下载的类型时，这个信息头回告诉浏览器这个文件的名字何类型(注意:当为application/pdf pdf浏览时,必须要依赖netflix-ribbon)
            String contentType = new MimetypesFileTypeMap().getContentType(fileName);
            response.setContentType(contentType);
            //设置编码
//            fileName = URLEncoder.encode(fileName, "UTF-8");
//            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,String.format("attachment; filename=%s", fileName));
            PdfUtil.doc2pdf(in,out);
            //IOUtils.copy(in,out);
        }catch (Exception e){
            throw new IllegalArgumentException(e) ;
        }
    }


    public static void main(String[] args) {

        String contentType = new MimetypesFileTypeMap().getContentType("xx.jpg");
        System.out.println(contentType);
    }
}
